<script lang="ts" setup>
	import { ref, onMounted, computed } from 'vue';
	import { createAppoint, getQuestions, getAdvisorys, getAdvisorysByTime } from '@/api/psychology/appointment.js'
	import { userInfo } from '@/store/Pinia/userInfo.js'
	import { isPhoneNum } from '@/common/phone.ts'

	const props = defineProps({
		id: {
			type: [String, Number],
			default: ''
		}
	})

	const cates = ["选择时间预约", "选择老师预约"]

	let curNow = ref('1');
	let timeShow = ref(true);
	let teachers = ref<any[]>([]);
	let theTeacher = ref({});
	let allQuestions = ref({});
	let time = ref('');
	let number = ref('');
	let an1 = ref();
	let an2 = ref();
	let an3 = ref();
	const answers = ref<any[]>([]);
	const littleShowPopup = ref(false)

	let fullDate = ref();
	const userInfoModel = userInfo()

	const year = ref(0)

	const getDate = computed(() => {
		return function (time) {
			const year = time.getFullYear(); // 获取年份
			const month = String(time.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
			const day = String(time.getDate()).padStart(2, '0'); // 获取日期，并补零
			return `${year}-${month}-${day}`
		}
	})

	onMounted(() => {
		appoint()//获取排班信息
	});
	const getAllQuestions = () => {
		let item = {
			problemState: "1"
		}
		getQuestions(item).then((res) => {
			allQuestions.value = res.data.data
			console.log('allQuestions:', allQuestions.value);
		}).catch((error) => {
			console.error('error:', error);
		})
	};

	// 自动保存 
	const exit = () => {
		littleShowPopup.value = true;

	}
	const goBack = () => {
		littleShowPopup.value = false;
	}

	interface answersList {
		an1 ?: String,
		an2 ?: String,
		an3 ?: String,
	}

	interface createItem {
		"cnId" ?: String | number,
		"stuId" ?: String,
		"consRoomId" ?: String,
		"reservationDate" ?: String,
		"reservationEndTime" ?: String,
		"reservationStartTime" ?: String,
		"consAdvisoryState" ?: String,
		"stuPhone" ?: String,
		"problemList" ?: any,
		"consCnDutyId" ?: String | number,
		"cnUser" ?: Object
	}

	const createItem = ref<createItem>({})
	const reserveInfo = ref<createItem>({})
	const answersObj = ref<answersList>({})
	const phone = ref("")

	const isPhoneN = ref(false)
	const checkPhone = (e) => {
		if (e.detail.value != "") {
			console.log()
			isPhoneN.value = !isPhoneNum(e.detail.value)
		}
	}

	const appoint = () => {
		let itemByTh = {
			"id": props.id,//根据排班对象的id查询
		}
		getAdvisorysByTime(itemByTh).then((res) => {
			reserveInfo.value = res.data.data[0]
		})
		getAllQuestions();

	}

	const confirmShow = ref(false)
	const confirm = () => {
		console.log('!isPhoneN', isPhoneNum(phone.value))
		if (isPhoneNum(phone.value) || phone.value == "") {
			confirmShow.value = true
		} else {
			uni.showToast({
				title: ' 手机号格式错误！ ',
				icon: 'error'
			})
		}
	}


	const save = () => {
		let item = {
			"consCnDutyId": props.id,
		}
		getAdvisorys(item).then((res) => {
			if (res.data.success) {
				// if (res.data.data < 1) {
					answers.value = [];
					answers.value.push({ name: allQuestions.value[0]?.name, value: an1.value });
					answers.value.push({ name: allQuestions.value[1]?.name, value: an2.value });
					answers.value.push({ name: allQuestions.value[2]?.name, value: an3.value });
					createItem.value.cnId = reserveInfo.value?.cnId
					createItem.value.stuId = userInfoModel.data.id
					createItem.value.consRoomId = reserveInfo.value?.consRoom?.id
					createItem.value.reservationDate = reserveInfo.value?.workDate
					createItem.value.reservationStartTime = reserveInfo.value?.workStartTime
					createItem.value.reservationEndTime = reserveInfo.value?.workEndTime
					createItem.value.consAdvisoryState = '1'
					createItem.value.consCnDutyId = props.id
					createItem.value.problemList = allQuestions.value
					createItem.value.stuPhone = phone.value
					createAppoint(createItem.value).then((res) => {
						if (res.data.success) {
							uni.showToast({
								title: '预约成功'
							})
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/appointment/index'
								})
							}, 500)
						}
					})
				// } else {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '预约失败，该时段已被预约'
				// 	})
				// }
			}
		})
	}


	let isEmpty = computed<boolean>(() => {
		return teachers.value.every((teacher : any) => teacher.date !== fullDate.value);
	});

	const getTime = computed(() => {
		return function (time) {
			if (time != undefined) {
				var dateObject = new Date(time);
				var timeString = dateObject.toLocaleTimeString('en-US', { hour12: false });

				return `${timeString}`
			} else {
				return time
			}
		}
	})

	const formmatTime = computed(() => {//将2023-12-14转换成12/14
		return function (tiem) {
			let dateString = tiem;

			// 创建日期对象
			let dateObject = new Date(dateString);

			// 提取月份和日期
			let month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始，所以需要加1
			let day = dateObject.getDate().toString().padStart(2, '0');

			// 创建新的格式
			let newFormat = `${month}/${day}`;

			return newFormat
		}
	})

	const back = () => {
		uni.navigateBack()
	}
	const timer = ref(null)
	const handleEnd = () => {
		timer.value.resetTime()
	}
</script>

<template>
	<articleTable ref="timer"></articleTable>
	<img :src="'@/../static/img/appoint/appoint-bg.svg'"
		style="opacity: 0.2;width: 45%;position: absolute;top: 50%;right: 0;" />
	<Navigator :fixed="true" background-color="transparent" status-bar title="心理预约申请表" left-icon="back" left-text="返回"
		class="absolute">
	</Navigator>
	<view @touchend="handleEnd" class="wh100p bg0078BB-003E94 flex-column " style="justify-content: center; align-items: center;">
		<u-modal :show="confirmShow" showCancelButton width="550rpx" @confirm="save" @cancel="confirmShow = false"
			confirmColor='#0078BB'>
			<view>
				<text style="font-size: 0.8rem;">是否确定提交</text>
			</view>
		</u-modal>
		<view class="wh100p" style="padding:1% 2%;box-sizing: border-box;z-index:2;">
			<view class="flex-column select-body">
				<view class="wh100p  consultant-details-box flex column-center">
					<view class="w100p" style="padding: 0px 0 0px; bgfffff">
						<uni-section class="mb-10 " titleFontSize="32rpx" style="padding: 1%;border-radius: 10px;"
							title="基本信息" type="line">
							<view class="reserve-info-box flex">
								<view class="content-term flex">
									<view class="content-term-title">姓名：</view>{{userInfoModel.data.name}}
								</view>
								<view class="content-term flex">
									<view class="content-term-title">性别：</view>{{userInfoModel.data.sex}}
								</view>
								<view class="content-term flex">
									<view class="content-term-title">预约咨询师：</view>{{reserveInfo?.cnUser?.realName}}
								</view>
								<view class="content-term flex">
									<view class="content-term-title">预约时间：</view>{{reserveInfo.workStartTime}}
									--{{reserveInfo.workEndTime}}
								</view>
							</view>
						</uni-section>

						<uni-section class="mb-10 mt14" titleFontSize="32rpx" style="padding: 1%;border-radius: 10px;"
							title="问题" type="line">
							<view class="w100p flex-center">
								<view class="w100p flex-column"
									style=" margin-bottom: 20rpx;padding: 10px;">
									<view class="flex w100p mb10 column-center">
										<view class="flex mb10 column-center" style="width: 65%;">
											<span class="mr20" style="line-height: 80rpx;font-weight: bold;">{{`联系电话:`}}
											</span>
											<input
												style="border: 1rpx solid rgb(226,230,234);border-radius: 10rpx;padding: 20rpx;flex: 1;"
												placeholder="请输入联系电话" v-model="phone" @focus="isPhoneN=false"
												:maxlength="11"
												@blur="checkPhone" />
										</view>
										<text v-show="isPhoneN" style="color: red;margin-left: 30px;">手机号格式错误</text>
									</view>
									<view v-for="(item,index) of allQuestions" style="width: 65%;">
										<span style="line-height: 80rpx;font-weight: bold;">{{item.name}}? </span>
										<textarea class="box-sizing"
											style="border: 1rpx solid rgb(226,230,234);border-radius: 10rpx;padding: 20rpx;height: 220rpx;width: 100%;"
											placeholder="请输入问题" v-model="item.value"></textarea>
									</view>
								</view>
							</view>

							<view class="w100p flex-center mt30 column-center">
								<view class="mr20">
									<button type="default" class="gui-button gui-color-white gui-border ">
										<text class="gui-color-black gui-button-text gui-border" style="padding: 60px;"
											@click="back">取消</text>
									</button>
								</view>
								<view>
									<button type="default" class="gui-button gui-bg-blue gui-noborder ">
										<text class="gui-color-white gui-button-text" style="padding: 60px;"
											@click="confirm">提交</text>
									</button>
								</view>
							</view>
						</uni-section>
					</view>
				</view>
			</view>
		</view>

	</view>


</template>

<style>
	.select-body {
		width: 1200px;
		height: 100%;
		margin: 0 auto;
		box-sizing: border-box;
	}

	.select-body .consultant-tabs {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
		height: 40px;
		margin-bottom: 30px;
	}

	.consultant-details-box {
		min-height: 560px;
		height: 100%;
	}

	.consultant-info-box {
		background: #fff;
		border-radius: 5px;
		width: 300px;
		margin-right: 30px;
		padding: 30px 20px;
		max-height: 500px;
		box-sizing: border-box;
	}

	.avatar-box {
		margin: 0 auto 12px;
		width: 128rpx;
		height: 128rpx;
		position: relative;
	}

	.cnUser-name {
		text-align: center;
		line-height: 25px;
		font-size: 18px;
		font-weight: 700;
		color: #333;
		margin-bottom: 6px;
	}

	.cnUser-phone,
	.cnUser-email {
		line-height: 20px;
		font-size: 14px;
		color: #333;
		margin-bottom: 2px;
		text-align: center;
	}

	.intro-content {
		background: #f4faff;
		border-radius: 5px;
		padding: 15px;
		color: #666;
		font-size: 12px;
		line-height: 20px;
		word-wrap: break-word;
	}

	.details-right {
		min-width: 30%;

		max-width: 870px;
		flex: 1
	}

	.time-box {

		background: #fff;
		border-radius: 5px;

	}

	.details-year {
		height: 128rpx;
		line-height: 128rpx;
		border-bottom: 1px solid #edf2fa;
		padding-left: 30px;
		color: #333;
		font-size: 24px;
		font-weight: 700;
	}

	.scheduling-item {
		padding-top: 15px;
		padding-bottom: 5px;
		border-bottom: 1px solid #edf2fa;
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
	}

	.scheduling-date {
		width: 50px;
		line-height: 22px;
		color: #333;
		font-size: 16px;
		font-weight: 700;
	}

	.date-scheduling {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
		-webkit-box-flex: 1;
		-ms-flex: 1;
		flex: 1;
	}

	.reserve-info-box {
		padding: 1% 20px;
		border-radius: 0 0 2px 2px;
		flex-wrap: wrap;
		box-sizing: border-box;
		justify-content: space-between;
	}

	.content-term {

		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		height: auto;
		line-height: 22px;

	}
</style>